package org.brisling.satisfaction.queryService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.exception.DangerousOperatorException;
import org.brisling.common.util.DateUtil;
import org.brisling.common.util.LongUtil;
import org.brisling.common.util.WhereUtil;
import org.brisling.satisfaction.domain.SatisEvaluate;
import org.brisling.satisfaction.domain.SatisRank;
import org.brisling.satisfaction.domain.SatisfactionQuestion;
import org.brisling.satisfaction.domain.VOSatisDeptDetail;
import org.brisling.satisfaction.domain.VOSatisfaction;
import org.brisling.satisfaction.domain.VOSatisfactionStatistic;
import org.brisling.satisfaction.domain.VOSatisfactionWindow;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/satisEvaluate/query")
public class QuerySatisEvaluateService extends AbstractBaseQueryService<SatisEvaluate>{
	
	
	@Autowired
	private QueryDictionaryService dicService;
	
	public QuerySatisEvaluateService(){
		this.moduleName = ConstSysParam.MODULE_SATISFACTION_EVALUATE;
		this.subSystem = ConstSysParam.SUBSYSTEM_STATISFACTION;
		this.tableName = "V_" +this.getTableName(SatisEvaluate.class);
		this.clazz = SatisEvaluate.class;	
		orderMap.put("evaluateat","desc");		
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	/**
	 * 门诊窗口满意度查询
	 * @return
	 */
	@RequestMapping("/windPage.action")
	public ModelAndView getWindowPage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate/window");
	}
	
	/**
	 * 门诊窗口满意度查询
	 * @return
	 */
	@RequestMapping("/windowDetailPage.action")
	public ModelAndView getWindowDetailPage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate/windowDetail");
	}
	
	/**
	 * 门诊问卷满意度查询
	 * @return
	 */
	@RequestMapping("/outpatientQuestionnairePage.action")
	public ModelAndView getOutPatientQuestionnairePage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate/outpatientQuestion");
	}
	/**
	 * 住院问卷满意度查询
	 * @return
	 */
	@RequestMapping("/inpatientQuestionnairePage.action")
	public ModelAndView getInPatientQuestionnairePage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate/inpatientQuestion");
	}
	
	/**
	 * 住院问卷满意度查询
	 * @return
	 */
	@RequestMapping("/inpatientQuestionDetailPage.action")
	public ModelAndView inpatientQuestionDetailPage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate/inpatientQuestionDetail");
	}
	
	/**
	 * 住院科室满意度查询
	 * @return
	 */
	@RequestMapping("/inpatientDeptPage.action")
	public ModelAndView getInPatientDeptPage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate/inpatientDept");
	}
	
	/**
	 * 住院科室满意度查询
	 * @return
	 */
	@RequestMapping("/inPatientDeptDetailPage.action")
	public ModelAndView getInPatientDeptDetailPage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate/inpatientDeptDetail");
	}
	
	/**
	 * 住院科室满意度明细查询
	 * @return
	 */
	@RequestMapping("/inpatientDetailQueryPage.action")
	public ModelAndView getInpatientDetailQueryPage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate/inpatientDetailQuery");
	}
	
	/**
	 * 满意度统计汇总页面
	 * @return
	 */
	@RequestMapping("/satisticPage.action")
	public ModelAndView getSatisticPage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate/all");
	}
	
	/**
	 * 满意度统计汇总页面
	 * @return
	 */
	@RequestMapping("/satisfactionInfoPage.action")
	public ModelAndView getSatisfactionInfoPage(){
		return new ModelAndView("/satisfaction/satisfaction_rank/popInfo");
	}
	
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getListDomain.action")
	public ListDomain<LinkedHashMap> getListDomain(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="sort",required=false) String sort){		
		
		
		return super.getPagedListDomain(page, rows);
	}	
	
	@RequestMapping("/getTreeListDomain.action")
	public ListDomain<SatisEvaluate> getTreeListDomain(@RequestParam(value="id",required=false) Long id){
		
		return this.getPagedTreeListDomain(id);
		
	}	
	
	

	/**
	 * 获取门诊问卷详细
	 */
	
	@RequestMapping("/getWindowQueDetail.action")
	public ListDomain<Object> getWindowQueDetail(@RequestBody(required=false) String body){		
		
		String sql = dicService.getSqlByBizcode("window_problem_all_detail");
		Map<String,Object> map = this.getTimeCondition(body);
		return super.getPagedClassListDomain(sql, map, SatisfactionQuestion.class,SatisfactionQuestion.class,false);	
		
	}
	
	
	/**
	 * 查询窗口满意度数据
	 * @param body
	 * @return
	 */
	
	@RequestMapping("/getWindowDomain.action")
	public ListDomain<Object> getWindowDomain(@RequestBody(required=false) String body){		
		
		String sql =dicService.getSqlByBizcode("satistic_window");		
		
		return 	super.getPagedClassListDomain(sql, body, SatisEvaluate.class, VOSatisfactionWindow.class,false);
		
	}
	
	/**
	 * 查询窗口满意度数据
	 * @param body
	 * @return
	 */
	
	@RequestMapping("/getWindowDetailDomain.action")
	public ListDomain<Object> getWindowDetailDomain(@RequestBody(required=false) String body){		
		
		String sql =dicService.getSqlByBizcode("satistic_window_detail");		
		
		return 	super.getPagedClassListDomain(sql, body, SatisEvaluate.class, VOSatisfactionWindow.class,false);
		
	}
	
	/**
	 * 查询窗口满意度数据
	 * @param body
	 * @return
	 */
	
	@RequestMapping("/getOutpatientQuestionDomain.action")
	public ListDomain<Object> getOutpatientQuestionDomain(@RequestBody(required=false) String body){		
		
		String sql = dicService.getSqlByBizcode("satisfaction_outpatient_questionnaire");
		Map<String,Object> map = this.getTimeCondition(body);
		return super.getPagedClassListDomain(sql, map, SatisfactionQuestion.class,VOSatisfaction.class,false);	
		
	}
	
	/**
	 * 查询窗口满意度数据
	 * @param body
	 * @return
	 */	
	@RequestMapping("/getInpatientQuestionDomain.action")
	public ListDomain<Object> getInpatientQuestionDomain(@RequestBody(required=false) String body){		
		
		String sql =dicService.getSqlByBizcode("satisfaction_inpatient_questionnaire");
		Map<String,Object> map = this.getTimeCondition(body);
		return super.getPagedClassListDomain(sql, map, SatisfactionQuestion.class,VOSatisfaction.class,false);	
		
	}
	
	/**
	 * 查询科室满意度评价数据明细
	 * @param body
	 * @return
	 */	
	@RequestMapping("/getInpatientQuestionDetailDomain.action")
	public ListDomain<Object> getInpatientQuestionDetailDomain(@RequestBody(required=false) String body){		
		
		String sql =dicService.getSqlByBizcode("satisfaction_inpatient_questionnaire_detail");
		Map<String,Object> map = this.getTimeCondition(body);
		return super.getPagedClassListDomain(sql, map, SatisfactionQuestion.class,SatisfactionQuestion.class,false);	
		
	}
	
	/**
	 * 查询科室满意度评价数据明细
	 * @param body
	 * @return
	 */	
	@RequestMapping("/getInpatientDetail.action")
	public ListDomain<Object> getInpatientDetail(@RequestBody(required=false) String body){		
		
		String sql =dicService.getSqlByBizcode("satisfaction_inpatient_questionnaire_detail");
		Map<String,Object> map = this.getTimeCondition(body);
		return super.getPagedClassListDomain(sql, map, SatisfactionQuestion.class,SatisfactionQuestion.class,false);	
		
	}
	
	
	
	
	/**
	 * 查询住院科室满意度数据
	 * @param body
	 * @return
	 */	
	@RequestMapping("/getInpatientDeptDomain.action")
	public ListDomain<Object> getInpatientDeptDomain(@RequestBody(required=false) String body){		
		
		String sql = dicService.getSqlByBizcode("satisfaction_inpatient_dept");
		
		
		sql +=" WHERE  i.patient_type = '2' AND i.data_type = '2' ";
		Map<String,Object> map = this.getTimeCondition(body);
		if(map.containsKey("_year_month")){
			Object obj =map.get("_year_month");
			if(obj!=null)
				sql +="AND i.monitor_year_month = '"+obj.toString()+"' ";
		}
		sql += " ORDER BY d.sortedid";
		return super.getPagedClassListDomain(sql, map, SatisfactionQuestion.class,VOSatisfaction.class,false);	
		
	}
	
	
	/**
	 * 查询窗口满意度数据
	 * @param body
	 * @return
	 */	
	@RequestMapping("/getInpatientDeptDetailDomain.action")
	public ListDomain<LinkedHashMap<String,String>> getInpatientDeptDetailDomain(@RequestBody(required=false) String body){		
		
		String sql = dicService.getSqlByBizcode("satisfaction_inpatient_dept_detail");
		
		Map<String,Object> conditionMap = this.getTimeCondition(body);
		Integer[] pages = LongUtil.getPageParam(conditionMap);
		
		Map<String,String> param = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
		
		String startTime = null;
		String stopTime = null;
		String depart_code = null;
		if(param.containsKey("evaluate_time_start")){
			
			Object obj = param.get("evaluate_time_start");			
			if(obj!=null)
				startTime = obj.toString();
		}
		if(param.containsKey("evaluate_time_end")){
			
			Object obj = param.get("evaluate_time_end");
			
			if(obj!=null)
				stopTime = obj.toString();
		}
		
		if(param.containsKey("depart_code")){
			Object obj = param.get("depart_code");
			if(obj!=null)
				depart_code = obj.toString();
		}
		if(startTime==null || stopTime==null || depart_code==null){
			return new ListDomain<LinkedHashMap<String,String>>();
		}
		sql = String.format(sql, startTime,stopTime,depart_code);
		
		List<VOSatisDeptDetail> lists = null;
		try {
			lists = super.getClassedAllList(sql, VOSatisDeptDetail.class);
			
		} catch (DangerousOperatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return getDeptDetail(lists);
		
	}
	
	private ListDomain<LinkedHashMap<String,String>> getDeptDetail(List<VOSatisDeptDetail> lists){
		
		ListDomain<LinkedHashMap<String,String>> retDomain = new ListDomain<LinkedHashMap<String,String>>();
		if(lists!=null && lists.size()>0){
			LinkedHashMap<String,List<VOSatisDeptDetail>> maps = new LinkedHashMap<String,List<VOSatisDeptDetail>>();
			
			
			//按照评价id组合同一次评价值到list中
			for(int i=0;i<lists.size();i++){
				VOSatisDeptDetail sd = lists.get(i);
				if(sd!=null && sd.getEvaluate_id()!=null){
					List<VOSatisDeptDetail> tmp_vo = null;
					if(maps.containsKey(sd.getEvaluate_id())){
						tmp_vo = maps.get(sd.getEvaluate_id());
					}else{
						tmp_vo = new ArrayList<VOSatisDeptDetail>();
					}
					tmp_vo.add(sd);
					maps.put(sd.getEvaluate_id(), tmp_vo);
				}
			}
			
			
			List<LinkedHashMap<String,String>> retList = new ArrayList<LinkedHashMap<String,String>>();
			
			Integer maxCount = 10;
			//根据组合后的list生成视图层vo
			for(Map.Entry<String, List<VOSatisDeptDetail>> elists:maps.entrySet()){
				List<VOSatisDeptDetail> groupLists = elists.getValue();
				
				//判断最大评价项数
				maxCount = maxCount>groupLists.size()?maxCount:groupLists.size();
				VOSatisDeptDetail td = groupLists.get(0);
				LinkedHashMap<String,String> tMap = new LinkedHashMap<String,String>();
				
				tMap.put("evaluate_id",td.getEvaluate_id());
				tMap.put("evaluate_problem_id",td.getEvaluate_problem_id());
				tMap.put("depart_code",td.getDepart_code());
				tMap.put("depart_name",td.getDepart_name());
				tMap.put("patient_name",td.getPatient_name());
				tMap.put("patient_no",td.getPatient_no());
				
				Integer count = 0;
				for(int i=0;i<groupLists.size();i++){
					VOSatisDeptDetail ld = groupLists.get(i);
					String _score = ld.getScore();
					_score = _score==null?"0":_score;
					count += LongUtil.getIntValue(_score,0);
					tMap.put(i+1 + "", ld.getScore());
				}		
				tMap.put("score_count",count+"");
				retList.add(tMap);
			}
			Integer countStandard = 5* maxCount;
			for(int i=0;i<retList.size();i++){
				retList.get(i).put("score_standard", countStandard+"");
			}
			retDomain.setTotal(new Long(maps.size()));
			retDomain.setRows(retList);
			
		}
		return retDomain;
	}
	
	/**
	 * 满意度统计汇总数据
	 * @param body
	 * @return
	 */	
	@RequestMapping("/getSatisfactionDomain.action")
	public ListDomain<Object> getSatisfactionDomain(@RequestBody(required=false) String body){		
		
		String sql =dicService.getSqlByBizcode("satisfaction_statistic_all");
		
		return super.getPagedClassListDomain(sql, body,SatisRank.class,VOSatisfactionStatistic.class,false);	
		
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/getStaticInfoAll.action")
	public LinkedHashMap getStaticInfoAll(@RequestBody(required=false) String body){		
		
		LinkedHashMap map = new LinkedHashMap(); 
		map.put("satisfaction_window", getWindowChart(body));		
		return map;
	}
	
	/**
	 * 获取窗口满意度图表数据
	 * @param body
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private List<LinkedHashMap> getWindowChart(String body){
		String sql =dicService.getSqlByBizcode("satisfaction_window_chart");
		HashMap<String,String> typeMap = this.getTypeMap(SatisEvaluate.class);
		Map<String,Object> map =getBodyParam(body);
		
		Map<String,String> conditionMap = null;
		if(map.containsKey("condition")){
			conditionMap = (Map<String, String>) map.get("condition");
		}else{
			conditionMap = new HashMap<String,String>();
		}
		if((map!=null) && (!map.isEmpty())){
			if(map.containsKey("date_start")){
				conditionMap.put("evaluateat_start", map.get("date_start").toString());
			}
			if(map.containsKey("date_end")){
				conditionMap.put("evaluateat_end", map.get("date_end").toString());
			}
		}
		String whereCorse = null;
		if((conditionMap!=null)&&(!conditionMap.isEmpty())){
			whereCorse = WhereUtil.getConditionWhereCorse(conditionMap, typeMap);			
		}
		whereCorse=whereCorse==null?"":" where " + whereCorse.trim();
		sql = String.format(sql, whereCorse);
		return super.getMappedList(sql);	
		
	}
	
	@RequestMapping("/getTreeList.action")
	public List<SatisEvaluate> getTreeList(@RequestParam(value="id",required=false) Long id){
		
		return this.getPagedTreeList(id);
		
	}	
	
	@RequestMapping("/getOne.action")
	public SatisEvaluate getOne(@RequestParam(value="id",required=false) Long id){
		return super.getOne(id);
	}

	/**
	 * 获取评价时间条件
	 * @param body
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Map<String,Object> getTimeCondition(String body){
		Map<String,Object> map = this.getBodyParam(body);
		
		String[] dates = DateUtil.getMapMonthDay(map);
		if(dates!=null && dates.length>0 && dates[0]!=null){
			Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
			paramMap.put("evaluate_time_start", dates[0]);
			paramMap.put("evaluate_time_end", dates[1]);
			
			map.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);
			map.put("_year_month", dates[2]);
		}
		
		return map;
	}
}
